FOR and WHILE loops are structured control flow statements.
A FOR loop will iterate once for each element in the range, and the WHILE iterates for as long as a condition holds.
However, inserting an EXIT
statement within the loop breaks this structure, reducing the code’s readability and making it harder to
debug.
Noncompliant code example
SET SERVEROUTPUT ON
DECLARE
TYPE myCollectionType IS VARRAY(10) OF VARCHAR2(42);
myCollection myCollectionType := myCollectionType('Foo', 'Bar', NULL, 'Baz', 'Qux');
i PLS_INTEGER;
BEGIN
i := 1;
WHILE i <= myCollection.LAST LOOP
EXIT WHEN myCollection(i) IS NULL; -- Noncompliant, breaks the structure of the WHILE
DBMS_OUTPUT.PUT_LINE('Got: ' || myCollection(i));
i := i + 1;
END LOOP;
Compliant solution
SET SERVEROUTPUT ON
DECLARE
TYPE myCollectionType IS VARRAY(10) OF VARCHAR2(42);
myCollection myCollectionType := myCollectionType('Foo', 'Bar', NULL, 'Baz', 'Qux');
i PLS_INTEGER;
BEGIN
i := 1;
WHILE i <= myCollection.LAST AND myCollection(i) IS NOT NULL LOOP
DBMS_OUTPUT.PUT_LINE('Got: ' || myCollection(i));
i := i + 1;
END LOOP;
END;
/